package com.faiz.algorithm;

import java.util.Arrays;
import java.util.Collections;

public class QuickSort {

    public void quickSort(int[] nums, int start, int end) {
        if (start >= end || nums == null) {
            return;
        }

        // 获取随机数
        int picked = (int) (Math.random() * (end - start + 1)) + start;
        // 将随机数和数组第一个数进行互换
        swap(nums, picked, start);

        // 下面则通过partition来对数组进行排序
        int pivot = nums[start];
        int index = start;
        for (int i = start + 1; i <= end; i++) {
            if (nums[i] <= pivot) {
                swap(nums, index + 1, i);
                index++;
            }
        }
        swap(nums, index, start);
        // 递归处理其余部分
        quickSort(nums, start, index - 1);
        quickSort(nums, index + 1, end);
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    public static void main(String[] args) {
        int num1 =9;
        int num2 = 8;
        int[] nums1 = {2, 2, 2, 1, 1, 1, 4, 3};
        QuickSort quickSort = new QuickSort();
        quickSort.quickSort(nums1, 0, nums1.length - 1);
        System.out.println(Arrays.toString(nums1));
    }
}
